package com.sxwl.auth.controller;

import com.sxwl.auth.config.JwtProperties;
import com.sxwl.auth.service.AuthService;
import com.sxwl.common.pojo.UserInfo;
import com.sxwl.common.utils.JwtUtils;
import com.sxwl.vo.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author reading
 * @Description TODO
 * @Date 2020/4/5 15:16
 */
@RestController
@Api("用户登录认证")
@RequestMapping("auth")
public class AuthController {
    @Autowired
    private AuthService authService;
    @Autowired
    private JwtProperties jwtProperties;
    //登录认证
    @PostMapping("login")
    @ApiOperation(value = "用户登录认证",notes = "对用户输入邮箱和密码登录认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name="email",value = "用户输入邮箱"),
            @ApiImplicitParam(name="password",value = "用户输入密码")
    })
    public JsonData login(@RequestParam("email") String email,
                          @RequestParam("password")String password){
        String token=  this.authService.login(email,password);
        // 登录校验
        if (StringUtils.isBlank(token)) {
            return JsonData.fail("登录认证失败");
        }
        //返回生成的token
        return JsonData.success(token,"生成token");
    }
    /**
     * 验证用户信息
     * @param token
     * @return
     */
    @GetMapping("verify")
    public JsonData verifyUser(@RequestParam("token")String token){
            // 从token中解析token信息
        try {
             UserInfo  user= JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            return  JsonData.success(user,"成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonData.fail("失败");
    }


}
